<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Basicdata;
use app\admin\model\Image;
use app\admin\model\Area;
use app\admin\model\Villages;

use think\Db;
use think\Exception;
use think\Request;

class Manages extends Base
{

    public function _initialize() {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['isDelete'] = ['neq', 1];
        $this->defaultWhere = $defaultWhere;
        $this->searchFields = [
            'name' => [
                'label'     => '主体名称',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        // 主体类型
        $typeList = get_managetype();
        // 经营类目
        $categoryList = Basicdata::where('type', 'managecate')->select();

        $this->assign('typeList', $typeList);
        $this->assign('categoryList', $categoryList);
    }

    public function index() {
        return parent::index();
    }

    public function add(Request $request) {

        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = '') {

        return parent::addPost($request, $this->redirect);
    }

    public function edit(Request $request) {
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        // 图集
        $imagesList = Image::where(['relatedId' => $info->id, 'tag' => 'imglist'])->where('imgUrl', 'neq', $info->imgUrl)->order('sorting ASC')->select();
        $this->assign('imagesList', $imagesList);

        $areaMdl = new Area();
        $city = Helper::makeOptions(
            $areaMdl,
            ['level' => 1],
            ['id' => 'asc']
        );
        $this->assign('city',$city);

        return $this->view->fetch($this->editView, [
            'info' => $info
        ]);
    }

    public function editPost(Request $request, $redirect = '') {
        $imagesList = Image::where(['relatedId' => $request->param('id'), 'tag' => 'imglist'])->order('sorting ASC')->select();
        $this->assign('imagesList', $imagesList);

        return parent::editPost($request, $this->redirect);
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        if($id){
            Db::startTrans();
            try{
                $result = $model->where('id', $id)->update(['isDelete' => 1]);
                if($result !== false){
                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 检查名称是否已存在
     */
    public function checkName(){
        if($this->request->isAjax()){
            $name = $this->request->param('name');
            $model = model($this->model);

            $result = $model->where(['name' => $name])->field('name')->find();

            if($result){
                return json(['status' => 1]);
            }else{
                return json(['status' => 0]);
            }
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            // 所在地
            $item['area'] = getArea($item);

            // 主体类型
            if($item['typeId']){
                $typeArr = get_managetype();
                $item['typeId'] = $typeArr[$item['typeId']];
            }
            // 经营类目
            if($item['categoryId']){
                $item['categoryId'] = Basicdata::where(['id' => $item['categoryId']])->value('name');
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }
            if(isset($filter['typeId']) && $filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if(isset($filter['categoryId']) && $filter['categoryId']){
                $where['categoryId'] = $filter['categoryId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

}
